﻿using DataBaseLib.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBaseLib
{
    public class MyDbContext
    {

        /// <summary>
        /// 数据库类型。
        /// </summary>
        public DbType DbType { get; set; }
        /// <summary>
        /// 连接字符串。
        /// </summary>
        public string ConnectionString { get; set; }
        /// <summary>
        /// 数据库类型。
        /// </summary>
        public SqlSugarScope Client { get; set; }

        public MyDbContext()
        {
            //默认采用配置项名
            //appSettings/DefaultDb 配置项为指定连接字符串的name
            var dbConfigName = ConfigurationManager.AppSettings["DefaultDB"];
            Init(dbConfigName);
        }

        public MyDbContext(string dbConfigName)
        {
            Init(dbConfigName);
        }

        public void Init(string dbConfigName) {
            var setting = ConfigurationManager.ConnectionStrings[1];
            if (setting == null)
            {
                this.ConnectionString = "Server=localhost;Database=CommonProject;Uid=root;Pwd=111111;SslMode=none";
            }
            if (!string.IsNullOrWhiteSpace(dbConfigName))
            {
                this.ConnectionString = setting.ConnectionString;
            }
            this.DbType = GetSugarDbType(setting);

            this.Client=new SqlSugarScope(new ConnectionConfig()
            {
                DbType=this.DbType,
                ConnectionString=ConnectionString,
                InitKeyType=InitKeyType.Attribute,
                IsAutoCloseConnection=true,//是否自动关闭连接
                AopEvents=new AopEvents {
                    OnLogExecuting = (sql, p) =>
                    {
                        //Console.WriteLine(sql);
                        //Console.WriteLine(string.Join(",",p?.Select(it=>it.ParameterName+":"+it.Value)));
                    }
                }
            });

            //如果不存在创建数据库存在不会重复创建 
            this.Client.DbMaintenance.CreateDatabase(); // 注意 ：Oracle和个别国产库需不支持该方法，需要手动建库  
                                                        //创建表根据实体类CodeFirstTable1     
            this.Client.CodeFirst.InitTables(typeof(Student));//这样一个表就能成功创建了
            this.Client.CodeFirst.InitTables(typeof(SupplierInfo));
            this.Client.CodeFirst.InitTables(typeof(CargoInfo));
            this.Client.CodeFirst.InitTables(typeof(CustomerInfo));
            this.Client.CodeFirst.InitTables(typeof(InStoreInfo));
            this.Client.CodeFirst.InitTables(typeof(InstoreOrderInfo));
            this.Client.CodeFirst.InitTables(typeof(LocationInfo));
            this.Client.CodeFirst.InitTables(typeof(OutStoreInfo));
            this.Client.CodeFirst.InitTables(typeof(OutStoreOrderInfo));
            this.Client.CodeFirst.InitTables(typeof(UserInfo));
            this.Client.CodeFirst.InitTables(typeof(WarehouseInfo));
        }


        /// <summary>
        /// 根据链接字符串的providerName决定那种数据库类型
        /// </summary>
        /// <param name="setting"></param>
        /// <returns></returns>
        private DbType GetSugarDbType(ConnectionStringSettings setting)
        {
            DbType dbType = DbType.SqlServer; //默认值
            var providerName = setting.ProviderName;
            if (providerName != null)
            {
                //数据库providerName：SqlClient MySqlClient SQLite OracleManaged/OracleClient Npgsql
                if (providerName.EndsWith(".SqlClient", StringComparison.OrdinalIgnoreCase))
                {
                    dbType = DbType.SqlServer;
                }
                else if (providerName.EndsWith(".MySqlClient", StringComparison.OrdinalIgnoreCase))
                {
                    dbType = DbType.MySql;
                }
                else if (providerName.EndsWith(".SQLite", StringComparison.OrdinalIgnoreCase))
                {
                    dbType = DbType.Sqlite;
                }
                else if (providerName.EndsWith("OracleManaged", StringComparison.OrdinalIgnoreCase))
                {
                    dbType = DbType.Oracle;
                }
                else if (providerName.EndsWith(".OracleClient", StringComparison.OrdinalIgnoreCase))
                {
                    dbType = DbType.Oracle;
                }
                else if (providerName.EndsWith("Npgsql", StringComparison.OrdinalIgnoreCase))
                {
                    dbType = DbType.PostgreSQL;
                }
                else if (providerName.EndsWith("Dm", StringComparison.OrdinalIgnoreCase))
                {
                    dbType = DbType.Dm;
                }
            }
            return dbType;
        }
    }
}
